'''
@Author: hua
@Date: 2019-04-17 09:43:46
@LastEditors: hua
@LastEditTime: 2019-05-20 08:39:26
'''
from aiohttp.web import middleware, Response
from aiohttp_session import get_session
from app.Vendor.tempDef import backStatus
from app.Model.Menu import Menu
from app.Model.AdminLog import AdminLog
import time

""" 行为操作记录 """
@middleware
async def Operation(request, handler):
    url = request.url.path.strip('/').split('/')
    isAdmin = url[0] if len(url)> 0 else ''
    controller = url[1] if len(url)> 1 else ''
    action = url[2] if len(url)> 2 else ''
    response = await handler(request)
    if isAdmin != 'fladmin':
        return response
    filters = {
        Menu.module == 'fladmin',
        Menu.controller ==  controller,
        Menu.action == action
    }

    menu = Menu().getOne(filters, Menu.id.desc())
    if menu == None:
        return response
    if 'name' not in menu.keys():
        return response
    menu_name  = menu['name']
    if controller !=  'login':
        data = dict()
        session =  await get_session(request)
        if 'admin_info' not in session.keys():
            return Response(status=302, headers={'Location':url+'/fladmin/index/index'})
        admin_info = session['admin_info']
        data['content'] = admin_info['name']+menu_name
        data['ip'] = request.remote
        data['admin_id'] = admin_info['id']
        data['admin_name'] = admin_info['name']
        data['route'] = 'fladmin/'+controller+'/'+action
        data['http_method'] = request.method
        data['add_time'] = time.time()
        AdminLog().add(data)
    return response


    
   